package com.sxf.djiuav;

import androidx.annotation.NonNull;
import dji.sdk.keyvalue.value.common.ComponentIndexType;
import dji.v5.common.callback.CommonCallbacks;
import dji.v5.common.error.IDJIError;
import dji.v5.manager.datacenter.livestream.LiveStreamManager;
import dji.v5.manager.datacenter.livestream.LiveStreamSettings;
import dji.v5.manager.datacenter.livestream.LiveStreamStatus;
import dji.v5.manager.datacenter.livestream.LiveStreamStatusListener;
import dji.v5.manager.datacenter.livestream.LiveStreamType;
import dji.v5.manager.datacenter.livestream.LiveVideoBitrateMode;
import dji.v5.manager.datacenter.livestream.StreamQuality;
import dji.v5.manager.datacenter.livestream.settings.RtspSettings;
import dji.v5.utils.common.LogUtils;

public class RtspLive {
    private static final String TAG = "RtspLive";
    private RtspSettings rtspSettings;
    private LiveStreamSettings liveStreamSettings;
    private LiveStreamStatusListener statusListener;
    private boolean isStreaming = false;
    private String localIpAddress = "192.168.88.187";
    private DJIApplication app = null;
    public RtspLive(DJIApplication app) {
        init(app);
    }

    private void init(DJIApplication application) {
        app = application;
        try {
            rtspSettings = new RtspSettings.Builder()
                    .setUserName("admin")
                    .setPassWord("123456")
                    .setPort(8554)
                    .build();
            // 使用Builder模式创建LiveStreamSettings实例
            liveStreamSettings = new LiveStreamSettings.Builder()
                    .setLiveStreamType(LiveStreamType.RTSP)
                    .setRtspSettings(rtspSettings)
                    .build();
            // 创建直播状态监听器
            statusListener = new LiveStreamStatusListener() {
                @Override
                public void onLiveStreamStatusUpdate(LiveStreamStatus status) {
                    // 处理直播状态更新
                    LogUtils.i(TAG, "Live stream status updated: " + status);
                    // 这里可以处理不同的状态码，如连接中、已连接、断开等
                    app.addLog("Live stream status updated: " + status);
                }
                @Override
                public void onError(IDJIError error) {
                    // 处理直播错误
                    LogUtils.e(TAG, "Live stream error: " + error.toString());
                    // 这里可以处理不同的错误码
                    app.addLog("Live stream error: " + error.toString());
                }
            };
            // 设置默认的RTSP参数
            setupDefaultRtspSettings();
            LogUtils.i(TAG, "RtspLive initialized with default settings");
            app.addLog("RtspLive initialized with default settings");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to initialize RtspLive: " + e.getMessage());
            app.addLog("Failed to initialize RtspLive: " + e.getMessage());
        }
    }

    private void setupDefaultRtspSettings() {
        try {
            setLiveStreamQuality(StreamQuality.HD);
            setLiveVideoBitRateMode(LiveVideoBitrateMode.AUTO);
            setLiveVideoBitrate(2500);
            setCameraIndex(ComponentIndexType.LEFT_OR_MAIN);
            LogUtils.i(TAG, "Default RTSP settings configured");
            app.addLog("Default RTSP settings configured");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to setup default RTSP settings: " + e.getMessage());
            app.addLog("Failed to setup default RTSP settings: " + e.getMessage());
        }
    }

    public void startStream() {
        if (isStreaming) {
            LogUtils.w(TAG, "Streaming is already in progress");
            app.addLog("Streaming is already in progress");
            return;
        }
        try {
            // 添加直播状态监听器
            addLiveStreamStatusListener();
            // 设置直播参数
            setLiveStreamSettings(liveStreamSettings);
            // 获取RTSP设置并配置服务器
            RtspSettings rtspSettings = liveStreamSettings.getRtspSettings();
            if (rtspSettings != null) {
                LogUtils.i(TAG, "RTSP server configured on port: " + rtspSettings.getPort());
                app.addLog("RTSP server configured on port: " + rtspSettings.getPort());
            }
            // 生成RTSP地址并打印
            String rtspUrl = generateRtspUrl();
            LogUtils.i(TAG, "RTSP URL: " + rtspUrl);
            app.addLog("RTSP URL: " + rtspUrl);
            // 调用LiveStreamManager开始直播
            LiveStreamManager.getInstance().startStream( new CommonCallbacks.CompletionCallback()
                 {
                     @Override
                     public void onSuccess()
                     {
                         isStreaming = true;
                         LogUtils.i(TAG, "RTSP live stream started successfully");
                         app.addLog("RTSP live stream started successfully");
                         LogUtils.i(TAG, "开启直播: " + generateRtspUrl());
                         app.addLog("开启直播: " + generateRtspUrl());
                     }
                     @Override
                     public void onFailure(@NonNull IDJIError error)
                     {
                         LogUtils.e(TAG, "开启直播错误: " + error.toString());
                         app.addLog("开启直播错误: " + error.toString());
                     }
                 }
            );
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to start stream: " + e.getMessage());
            app.addLog("Failed to start stream: " + e.getMessage());
            isStreaming = false;
        }
    }

    /**
     * 停止RTSP直播
     */
    public void stopStream() {
        if (!isStreaming) {
            LogUtils.w(TAG, "Streaming is not in progress");
            return;
        }
        try {
            // 调用LiveStreamManager停止直播
            LiveStreamManager.getInstance().stopStream( new CommonCallbacks.CompletionCallback()
                 {
                     @Override
                     public void onSuccess()
                     {
                         LogUtils.i(TAG, "停止直播: ");
                         app.addLog("停止直播: ");
                     }
                     @Override
                     public void onFailure(@NonNull IDJIError error)
                     {
                         LogUtils.e(TAG, "停止直播错误: " + error.toString());
                         app.addLog("停止直播错误: " + error.toString());
                     }
                 }
            );
            isStreaming = false;
            // 移除直播状态监听器
            removeLiveStreamStatusListener();
            LogUtils.i(TAG, "RTSP live stream stopped successfully");
            app.addLog("RTSP live stream stopped successfully");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to stop stream: " + e.getMessage());
            app.addLog("Failed to stop stream: " + e.getMessage());
        }
    }

    /**
     * 生成RTSP地址
     * @return 完整的RTSP URL
     */
    private String generateRtspUrl() {
        RtspSettings rtspSettings = liveStreamSettings.getRtspSettings();
        if (rtspSettings != null) {
            // RTSP地址格式: rtsp://username:password@ip:port/streaming/live/1
            return "rtsp://" + rtspSettings.getUserName() + ":" + rtspSettings.getPassword() +
                    "@" + localIpAddress + ":" + rtspSettings.getPort() + "/streaming/live/1";
        }
        return "";
    }

    /**
     * 设置直播状态的监听器
     */
    public void addLiveStreamStatusListener() {
        try {
            // 注册监听器到LiveStreamManager
            LiveStreamManager.getInstance().addLiveStreamStatusListener(statusListener);
            LogUtils.i(TAG, "Live stream status listener added");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to add live stream status listener: " + e.getMessage());
        }
    }

    /**
     * 删除直播状态的监听器
     */
    public void removeLiveStreamStatusListener() {
        try {
            // 从LiveStreamManager移除监听器
            LiveStreamManager.getInstance().removeLiveStreamStatusListener(statusListener);
            LogUtils.i(TAG, "Live stream status listener removed");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to remove live stream status listener: " + e.getMessage());
        }
    }

    /**
     * 设置直播参数
     * @param settings 直播参数设置
     */
    public void setLiveStreamSettings(LiveStreamSettings settings) {
        try {
            this.liveStreamSettings = settings;
            // 更新LiveStreamManager的设置
            LiveStreamManager.getInstance().setLiveStreamSettings(settings);
            LogUtils.i(TAG, "Live stream settings updated");
            app.addLog("Live stream settings updated");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to set live stream settings: " + e.getMessage());
            app.addLog("Failed to set live stream settings: " + e.getMessage());
        }
    }

    /**
     * 获取直播参数
     * @return 当前直播参数设置
     */
    public LiveStreamSettings getLiveStreamSettings() {
        return liveStreamSettings;
    }
    /**
     * 设置相机索引
     * @param index 相机索引
     */
    public void setCameraIndex(ComponentIndexType index) {
        try {
            // 在实际实现中，这里会设置相机索引
            LiveStreamManager.getInstance().setCameraIndex(index);
            LogUtils.i(TAG, "Camera index set to: " + index);
            app.addLog("Camera index set to: " + index);
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to set camera index: " + e.getMessage());
            app.addLog("Failed to set camera index: " + e.getMessage());
        }
    }
    /**
     * 获取相机索引
     * @return 当前相机索引
     */
    public ComponentIndexType getCameraIndex() {
        try {
            return LiveStreamManager.getInstance().getCameraIndex();
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to get camera index: " + e.getMessage());
            return ComponentIndexType.LEFT_OR_MAIN;
        }
    }
    /**
     * 设置直播视频质量类型
     * @param quality 视频质量
     */
    public void setLiveStreamQuality(StreamQuality quality) {
        try {
            // 在实际实现中，这里会设置视频质量
            LiveStreamManager.getInstance().setLiveStreamQuality(quality);
            LogUtils.i(TAG, "Stream quality set to: " + quality);
            app.addLog("Stream quality set to: " + quality);
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to set stream quality: " + e.getMessage());
            app.addLog("Failed to set stream quality: " + e.getMessage());
        }
    }

    /**
     * 获取直播视频质量类型
     * @return 当前视频质量
     */
    public StreamQuality  getLiveStreamQuality() {
        try {
            return LiveStreamManager.getInstance().getLiveStreamQuality();
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to get stream quality: " + e.getMessage());
            return StreamQuality.HD;
        }
    }

    /**
     * 设置直播码率模式
     * @param mode 码率模式（恒定码率/可变码率）
     */
    public void setLiveVideoBitRateMode(LiveVideoBitrateMode mode) {
        try {
            // 在实际实现中，这里会设置码率模式
            LiveStreamManager.getInstance().setLiveVideoBitrateMode(mode);
            LogUtils.i(TAG, "Bitrate mode set to: " + mode);
            app.addLog("Bitrate mode set to: " + mode);
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to set bitrate mode: " + e.getMessage());
            app.addLog("Failed to set bitrate mode: " + e.getMessage());
        }
    }

    /**
     * 获取直播码率模式
     * @return 当前码率模式
     */
    public LiveVideoBitrateMode getLiveVideoBitRateMode() {
        try {
            return LiveStreamManager.getInstance().getLiveVideoBitrateMode();
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to get bitrate mode: " + e.getMessage());
            return LiveVideoBitrateMode.AUTO;
        }
    }

    /**
     * 设置直播码率
     * @param bitrate 码率值（Kbps）
     */
    public void setLiveVideoBitrate(int bitrate) {
        try {
            // 在实际实现中，这里会设置码率
            LiveStreamManager.getInstance().setLiveVideoBitrate(bitrate);
            LogUtils.i(TAG, "Bitrate set to: " + bitrate + " Kbps");
            app.addLog("Bitrate set to: " + bitrate + " Kbps");
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to set bitrate: " + e.getMessage());
            app.addLog("Failed to set bitrate: " + e.getMessage());
        }
    }
    /**
     * 获取直播码率
     * @return 当前码率值
     */
    public int getLiveVideoBitrate() {
        try {
            return LiveStreamManager.getInstance().getLiveVideoBitrate();
        } catch (Exception e) {
            LogUtils.e(TAG, "Failed to get bitrate: " + e.getMessage());
            return 2500;
        }
    }

    /**
     * 设置本地IP地址
     * @param ipAddress 本机IP地址
     */
    public void setLocalIpAddress(String ipAddress) {
        this.localIpAddress = ipAddress;
        LogUtils.i(TAG, "Local IP address set to: " + ipAddress);
        app.addLog("Local IP address set to: " + ipAddress);
    }

    /**
     * 获取本地IP地址
     * @return 当前本地IP地址
     */
    public String getLocalIpAddress() {
        return localIpAddress;
    }

    /**
     * 获取当前直播状态
     * @return true表示正在直播，false表示未直播
     */
    public boolean isStreaming() {
        return isStreaming;
    }
}
